import pymysql

class DBUtil(object):
    __conn = None

    @classmethod
    def __connect_db(cls):
        if cls.__conn is None:
            cls.__conn = pymysql.connect(host="211.103.136.244", port=7068, user="student",password="KDTX_student_202304",database="huike", charset="utf8")
            return cls.__conn

    @classmethod
    def __close_db(cls):
        # 关闭游标
        if cls.__conn:
            cls.__conn.close()
            cls.__conn = None

    # 查询数据进行封装
    @classmethod
    def get_one(cls, sql):
        cursor = None
        result = None
        try:
            conn = cls.__connect_db()
            cursor = conn.cursor()
            cursor.execute(sql)
            result = cursor.fetchall()
            print(result)
        except Exception as e:
            print(e)
        finally:
            if cursor:
                cursor.close()
            cls.__close_db()
            print(result)
            return result

    # 对数据增删改的封装
    @classmethod
    def uid_db(cls, sql):
        cursor = None
        try:
            conn = cls.__connect_db()
            cursor = conn.cursor()
            cursor.execute(sql)
            cls.__conn.commit()
        except Exception as e:
            print(e)
            cls.__conn.rollback()
        finally:
            if cursor:
                cursor.close()
            cls.__close_db()

if  __name__ == "__main__":
    sql1 = "select name from tb_course;"
    print(DBUtil.get_one(sql1))

    sql2 = "delete from tb_course where name = '小天才睿智手表666666666666'"
    DBUtil.uid_db(sql2)

    sql3 = "select name from tb_course;"
    print(DBUtil.get_one(sql3))